/** @jsxImportSource @emotion/react */
//import { jsx } from "@emotion/react";
import * as React from "react";
//import { usePaginateQueryTask } from "./db";
import {
    List,
    ListItem,
    Avatar,Stack, StackTitle, StackItem,
    MenuItem,
    Text,
    useTheme,
    IconChevronRight,
    useMMenuBarOcup,
    VerticalMenu,
    DdMenuItem,
    Button,
    IconLayers,
    Dialog,
    DialogContent,
    DialogHeading,
    DialogDescription, InputLine, CommitInput, Input, ButtonRefComp, DialogClose
} from "customize-easy-ui-component";
//import { SearchBox } from "../SearchBox";
//import debug from "debug";
//import algoliasearch from "algoliasearch";
//import config from "./firebase-config";
//import { useSession } from "../auth";
//import find from "lodash.find";
//import { useDeleteRequestFollow, usePaginateQueryUser,  } from "./db";
//import { StackItem } from "react-gesture-stack";
//import { useLocation } from "wouter";
//import { BoundReports } from "./report/BoundReports";
import {usePaginationFragment, useRefetchableFragment, useRelayEnvironment} from "react-relay/hooks";
import {MySubReport$key} from "./__generated__/MySubReport.graphql";
import {useContext, } from "react";
import RoutingContext from "../routing/RoutingContext";
import {RecordSource} from "relay-runtime";
import {css} from "@emotion/react";
import {ChooseUnit} from "../unit/ChooseUnit";
// import {Stack, StackTitle, StackItem,} from "../../UiDebugSave/sample/Stack";

const graphql = require("babel-plugin-relay/macro");


interface MySubReportProps {
    isps: MySubReport$key;
}

export const MySubReport: React.FunctionComponent<MySubReportProps> = props => {
  const theme = useTheme();
  //const toast = useToast();
 // const {user,} = useSession();
  //const [, setLocation] = useLocation();
  //graphQl的查询usexxx钩子函数，无法主动从后端读取最新数据。
  //const { loading, userList:followings } = useFollowerIngs(false);
  let filtercomp={filter: { id:1 },
    offset:0,
    limit:5,
    orderBy: "id",
    asc: false
  };
  //const { loading, items:followings ,} = usePaginateQueryTask(filtercomp,check);
    const { data, refetch , loadNext,hasNext,isLoadingNext} = usePaginationFragment(
        graphql`
            fragment MySubReport on Query
            @refetchable(queryName: "findMeSubReportsQuery") {
                findMeSubReports(where: $swhere,after:$after,first:$first,orderBy:$orderByS,asc:$asc)
                @connection(key: "Query_findMeSubReports") {
                    edges {
                        node {id,type,modeltype,modelversion, stm{id,sta}
                            isp{
                                id,no,entrust,conclusion,dev{id,oid,cod},bus{id task{id,date}}
                            }
                        }
                    }
                }
            }
        `,
        props.isps,
    );
    const { findMeSubReports:list, }=data;
    //改成了let而不是常规的 const  下面点击列表允许能够直接删除列表被点击那一条对应的isps;
    const reps = list!.edges!.map( (edge : any) => edge?.node);
  //搜索user的输入:
  const [query, setQuery] = React.useState("");

  //状态管理　relation＝当前显示的或者按钮点击事件产生,关注的user是谁。 null as any告警去除
  const [relation, setRelation] = React.useState(null as any);


  const [, setFilter] = React.useState({where:
        {cod:query },
     });

  const noUsers = !query && (reps.length === 0);
  //界面轮播 setIndex切换显示界面；   //index不是组件外部那一个同名index；
  const [index, setIndex] = React.useState(0);
    const {history } = useContext(RoutingContext);

  function showRelation(item: any) {
    console.log("点击showRelation？item=", item);
    setRelation(item);
    setIndex(1);
  }

  React.useEffect(() => {
    //console.log("伪善setQueryResul02=" ,query,usersFind);
    let filtercomp={where:
        {cod:query },
      offset:0,
      first:5,
      orderBy: "useDt",
      asc: false
    };
    setFilter(filtercomp);
  }, [query]);
  //这两个useEffect的前后顺序不能颠倒，顺序非常重要，后面的依赖于前面的useEffect更新结果。
  //操作UI副作用；要进一步做修正性处理。
    const {barHeight } = useMMenuBarOcup(history.routeData?.isExact);
    const {save, field}= window.history.state?.state??{};
    const [open, setOpen] = React.useState(save?.open || false);
    const filt= JSON.parse(sessionStorage['分项报告过滤']??'{}');
    const [servu, setServu] = React.useState(save?.servu || filt?.servu);
    const [cod, setCod] = React.useState<any>(save?.cod || filt?.cod);
    const [oid, setOid] = React.useState<any>(save?.oid || filt?.oid);
    const [ident, setIdent] = React.useState<any>(save?.ident || filt?.ident);
    const [no, setNo] = React.useState<any>(save?.no ||filt?.no);
    async function pseudoDiasave() {
        return { open,cod,oid,servu,ident,no };
    }
    const commitBlurRef =React.useRef<HTMLDivElement | null>(null);

  return (
    <Stack
        navStyle={css({ position: 'sticky',  top: 0,})}
              style={{
                  overflow: 'unset',
                  height: '100%',
              }}
      index={index}
      navHeight={40}
      onIndexChange={i => setIndex(i)}
      items={[
        {
          title: (
              <StackTitle
                  contentAfter={
                  <>
                      <VerticalMenu>
                          <DdMenuItem label="刷新吧" onClick={(e) => {
                              refetch({}, { fetchPolicy: "network-only"});
                          }}/>
                      </VerticalMenu>
                      <MenuItem variant="ghost"  tight
                                onClick={() => {
                                    setOpen(true)
                                }}
                      >
                          <IconLayers />
                      </MenuItem>
                      <Dialog open={open} onOpenChange={setOpen}>
                          <DialogContent >
                              <DialogHeading>
                                  分项报告过滤器
                              </DialogHeading>
                              <DialogDescription>
                                  <div css={{ padding: '0 1rem' }}>
                                      <form  method="get"  action="/"  css={{margin: 0, position: "relative" }}>
                                          <div>
                                              <InputLine label={`设备代码:`}>
                                                  <CommitInput type="search" placeholder="精确匹配"
                                                               value={cod || ''}   onSave={txt => setCod(txt||undefined) }
                                                  />
                                              </InputLine>
                                              <InputLine label={`监察识别码:`}>
                                                  <CommitInput type="search" placeholder="精确匹配"
                                                               value={oid || ''}   onSave={txt => setOid(txt||undefined) }
                                                  />
                                              </InputLine>
                                              <InputLine label={`服务单位(进入挑选):`}>
                                                  <ChooseUnit id={servu?.id} name={servu?.name} field={'servu'}
                                                              autoFocus={field==='servu'}  onCancel={() => { setServu(undefined) }}
                                                              onDialog={async () => { return await pseudoDiasave() } }
                                                  />
                                              </InputLine>
                                              <InputLine label={`报告附加标识:`}>
                                                  <CommitInput  type="search"
                                                                value={ident || ''}  onSave={txt => setIdent(txt||undefined) }
                                                  />
                                              </InputLine>
                                              <InputLine label={`报告编号:`}>
                                                  <CommitInput type="search"
                                                               value={no || ''}  onSave={txt => setNo(txt||undefined) }
                                                  />
                                              </InputLine>
                                              <div
                                                  css={{
                                                      display: "flex",
                                                      marginTop: theme.spaces.lg,
                                                      justifyContent: "flex-end"
                                                  }}
                                              >
                                                  <Input  type='reset'  value={'清空过滤'}
                                                          style={{margin: 'auto', width: undefined }}  css={{backgroundColor: 'wheat' }}
                                                          onClick={async () => {
                                                              setCod(undefined); setOid(undefined); setIdent(undefined);
                                                              setNo(undefined); setServu(undefined);
                                                          } }
                                                  />
                                                  <ButtonRefComp intent="primary"
                                                                 ref={commitBlurRef}  onPointerOver={(e :any) => { commitBlurRef!.current!.focus(); }}
                                                                 onPress={() => {
                                                                     setOpen(false);
                                                                     sessionStorage['分项报告过滤'] =JSON.stringify({cod,oid,servu,ident,no});
                                                                     history.push("/inspect", {time: Date()} );
                                                                     console.log(`刚设置检验列表过滤:`, sessionStorage['分项报告过滤']);
                                                                 } }
                                                  >
                                                      过滤器改完重查
                                                  </ButtonRefComp>
                                              </div>
                                              </div>
                                      </form>
                                  </div>
                              </DialogDescription>
                              <DialogClose>关闭</DialogClose>
                          </DialogContent>
                      </Dialog>
                  </>
                  }
                  title={"我的独立分项报告列表"}
              />
          ),
          content: (
              <StackItem  css={{
                          marginBottom: `${barHeight}`,
                      }}
                     style={{  boxShadow:undefined }}
              >
              <div
                css={{
                  overflowY: "auto",
                  //overflowY: "scroll", 滚动触发，小屏幕很明显的条，滚动条会随浏览器屏幕设备模式变化样式。
                  height: "100%",
                }}
              >
                { noUsers && (
                  <Text
                    muted
                    css={{
                      fontSize: theme.fontSizes[0],
                      display: "block",
                      margin: theme.spaces.lg
                    }}
                  >
                    队列为空
                  </Text>
                )}
                  { !noUsers && (
                <List>
                 {reps?.map((item :any,i:number) => {
                   //这样的<RouterLink <ListItem onPress={() =>showRelation ;可能会ListItem报错unmounted:仅当嵌入为报告/动态模板之内；
                   return (
                       item && <ListItem
                        key={item?.id}
                        interactive={ true }
                        onPress={async (e) => {
                          e?.stopPropagation();
                          e?.preventDefault();
                          history.push(`/inspect/${item?.isp.id}/report/${item?.id}`);
                        } }
                        contentBefore={
                          <Avatar
                            size="sm"
                            src={item?.id}
                            name={item?.id}
                          />
                        }
                        primary={`${item?.isp.dev?.cod}`}
                        secondary={ `报告号: ${item?.isp.no||''}` }
                        contentAfter={
                            <IconChevronRight
                              color={theme.colors.text.muted}
                              aria-hidden
                            />
                        }
                      >
                        {`${item?.isp.dev?.oid} 日期:${item?.isp.bus?.task?.date}`}
                      </ListItem>
                    );
                  })}
                </List>
                  )}

                  <div css={{textAlign: "center", paddingBottom:'3rem' }}>
                      <Button disabled={isLoadingNext}
                              onPress={async (e) => {
                                  await loadNext(10,{  });
                              } }
                      >
                          {hasNext? '按，拉扯获取更多...':'没有更多了'}
                      </Button>
                  </div>
              </div>
            </StackItem>
          )
        }

      ]}
    />
  );

};





//报错Cannot read property 'map' of null标记出错代码行，竟可能会差错！实际错误点实在下方，报错指示却在上方的代码行，两处都有.map的代码。
//<Stack 组件，实际上是内部状态控制界面的呈现，实际上DOM数据内容并没有同步地变更，只是页面切换着看；适用数据库组织的；PK的，导航堆叠场景实际是源代码组织的。
//幸运的事！！<StackItem>底下内嵌的组件可以做到每一个都是独立自主的。这里<FollowingRecipes key={}/>对每一个按钮进入和后退的，虽然组件同一个，但内部状态数据可各自独立的。
//overflowY:"scroll"若遇到 css={{height: "100%", 和 minHeight: '300px' 不能同时添加的。overflowY:和"100%"一起使用，且要在内层DIV上用。组件中间层可能屏蔽掉。
//多层DIV的height: "100%", 需要在中间层次添加100%传递父辈限制大小，配合内部层的overflowY: "scroll",才能滚动。
//<Stack多层的下沉层叠＋<ListItem，配合<RouterLink，可以触发点击链接同时还能够下沉页面触发；左右两个页面都能刷新，可是小屏幕只能对照右半部分的核心界面。不触发下沉和要触发条目可同时用。
//点击一次触发多重：<RouterLink to={`/inspect/${item.id}`} >    /  <ListItem  onPress={() =>      /   <Button  onPress={e => { ；；
